<?php
/**
 * Created By base
 * Author: Virus
 * Date: 2020/3/17
 * Time: 18:40
 */

namespace app\admin\controller;


use app\admin\logic\AdminLogic;
use think\captcha\Captcha;
use think\model\concern\SoftDelete;
use think\Request;

class Login extends Error
{
    public function index()
    {
        if (session('uid')) {
            $this->success('您已登录，正在为您跳转到后台页面', url('admin/index/index'));
        } else {
            if (config('site.SHOW_VERIFY') == 1) {
                $this->assign('show_verify', 1);
            } else {
                $this->assign('show_verify', 0);
            }
        }

        return view();
    }

    public function verify()
    {
        ob_clean(); // 清除验证码
        $captcha           = new Captcha();
        $captcha->fontSize = config('site.CODE_FONT_SIZE');
        $captcha->length   = config('site.CODE_LEN');
        $captcha->useNoise = config('site.CODE_NOISE');
        $captcha->useCurve = config('site.CODE_CURVE');

        return $captcha->entry();
    }

    public function checkLogin(Request $request)
    {
        if ($request->isAjax()) {
            $username = input('post.username');
            $password = input('post.password');
            $code     = input('code');

            if (empty($code) && config('site.SHOW_VERIFY') == 1) {
                return writeJson(0, '验证码参数错误');
            }

            if (config('site.SHOW_VERIFY') == 1) {
                $captcha = new Captcha();
                if (!$captcha->check($code)) {
                    return writeJson(0, '验证码错误');
                }
            }

            // 判断ip地址限制登录是否开启
            $ip_state = config('site.WEB_IP_STATE');
            if ($ip_state == 1) {
                $ip           = $this->request->ip();
                $loginip_data = (new \app\common\model\mysql\Ip())->getField(
                    ['status' => 1],
                    'ip_address',
                    'id'
                );
                if (!in_array($ip, $loginip_data)) {
                    return writeJson(0, '非法登录，ip地址为:'.$ip.'不合法');
                }
            }

            $res = (new AdminLogic)->login($username, $password);
            if ($res) {
                return writeJson(1, '登录成功...正在跳转');
            }
            $this->error('用户不存在或密码错误');
        }
        $this->error('请求不合法');
    }

    public function logout()
    {
        session('uid', null);
        session('username', null);
        session('nickname', null);
        $this->success('退出成功', url('Login/index'));
    }
}